package com.cj.myblog.service.impl;

import com.cj.myblog.constants.ResultEnum;
import com.cj.myblog.dao.ArticleRepository;
import com.cj.myblog.dao.PartRepository;
import com.cj.myblog.model.ArticleDef;
import com.cj.myblog.model.PartDo;
import com.cj.myblog.model.Result;
import com.cj.myblog.service.PartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * Created by Administrator on 2017-08-30.
 */
@Service
public class PartServiceImpl implements PartService {


    @Autowired
    private PartRepository partRepository;

    @Autowired
    private ArticleRepository articleRepository;

    @Override
    public Result<List<PartDo>> findAll() {
        List<PartDo> list = partRepository.findAll();
        List<ArticleDef> rows = articleRepository.findCountByPartIdGroup();
        for (PartDo partDo:list) {
            for (ArticleDef def:rows){
                if (Objects.equals(def.getPartId(), partDo.getId())){
                    partDo.setCount(Integer.parseInt(def.getCount().toString()));
                }
            }
        }
        return new Result<>(list);
    }

    @Override
    @Transactional
    public Result<String> save(PartDo partDo) {
        PartDo DO = partRepository.save(partDo);
        Result<String> result = new Result<>();
        if (DO == null){
            result = new Result<String>(ResultEnum.SAVE_ERROR);
        }
        return result;
    }

    @Override
    public PartDo findOne(Long id) {
        PartDo partDo = partRepository.findOne(id);
        return partDo;
    }

    @Override
    public void delete(Long id) {
        partRepository.delete(id);
    }

    @Override
    public List<PartDo> findByStatus(int status) {
        List<PartDo> list =  partRepository.findByStatus(status);
        for (PartDo partDo:list) {
            partDo.setUrl("/list/" + partDo.getId());
        }
        return list;
    }



}
